<style scoped>
    .doc-preview {
        overflow: auto;
        zoom:0.4;
        height:700px;
        border: 1px dashed #eee;
    }
    
    .statements p {
        font-size: 18px;
    }

    .asd-inline {
        background-color: #f8f8f9;
        border-radius: 4px;
        padding: 8px 15px;
        margin: 8px 0;
        font-size: 14px;
        border: 1px solid #edeff0;
        position: relative;
    }    

    .total-price {
        color: #f90;
        /*font-size: 32px;*/
    }
</style>
<template>
    <div>
        <div class="ivu-mt">
            <el-card :bordered="false">
                <p class="card-title">
                    {{$t('message.term.doc_confirm')}}
                </p>
                <el-divider dashed />
                <el-row>
                    <el-col :span="11">
                    <StretchTable height="319" :columns="columnsDefinition" :data="dataList" @on-selection-change="onDocSelectChange" highlight-row @on-row-click="onRowClick"></StretchTable>
                    <div class="asd-inline card-title">
                        <el-row>
                            <el-col :span="12">总价({{selectionState}})</el-col>
                            <el-col :span="12" style="text-align: right;">{{this.totalPriceWithoutDiscount}} 元</el-col>
                        </el-row>
                    </div>
                    </el-col>
                    <el-col :span="13" ref="docPreviewCol" style="padding: 2px 0 2px 15px;">
                    <div style="color: #515a6e;font-weight: bold;padding: 8px 0;">预览</div>
                    <div ref="docPreview" class="doc-preview" v-html='docHTML'></div>
                    </el-col>
                </el-row>
            </el-card>
        </div>
        <div class="ivu-mt">
            <el-card :bordered="false">
                <!--<p class="card-title">
                    结算
                </p>
                <Divider dashed /> -->
                <p class="card-title" style="margin-bottom: 20px">
                    使用优惠券
                </p>
                <el-select v-model="custormerDiscountRelationIdSelected" clearable style="width:200px">
                    <el-option v-for="item in custormerDiscountList" :value="item.value" :key="item.value">{{ item.label }}</el-option>
                </el-select>
                <el-divider dashed />
                <div class="statements">
                    <p>
                        <!--<span class="ivu-avatar ivu-avatar-circle ivu-avatar-icon ivu-avatar-small" style="color: rgb(115, 209, 61); background-color: rgb(246, 255, 237);">
                            <i class="ivu-icon ivu-icon-logo-usd"></i></span>-->
                        <span>总费用:</span> <span class="total-price"> {{totalPrice}} </span><span>元</span>
                    </p>
                </div>
                <el-divider dashed />
                <el-form ref="form" :model="form" :rules="ruleValidate" label-position="top">
                    <el-form-item label="邮箱地址" prop="email">
                        <el-input v-model="form.email" prefix="ios-mail-outline" placeholder="请输入接收文档的邮箱地址" style="width: 300px" />
                        <!--<Button type="default" @click="saveEmailAddressAsDefault()">保存为默认邮箱</Button>-->
                    </el-form-item>
                </el-form>
                <!--
                <Divider dashed />
                <p class="card-title">
                    备注
                </p>
                <Input v-model="remark" type="textarea" :rows="4" /> -->
                <el-divider dashed />
                <div style="text-align: right;  margin-top: 20px">
                    <div style="float: left">
                        <el-button @click="backStep()">返回</el-button>
                    </div>
                    <el-button type="success" @click="nextStep()">下一步</el-button>
                </div>
            </el-card>
        </div>
    </div>
</template>
<script>
import { API } from '@/customized/http/api';
import StretchTable from '@/views/components/stretch-table/stretch-table.vue';
export default {
    /*从父路由注入父路由页面的函数*/
    inject: ['next', 'back'],
    components: {
      StretchTable
    },
    data() {
        return {
            docHTML: "",
            columnsDefinition: [{
                    type: 'selection',
                    width: 55
                },
                {
                    title: '文件名',
                    key: 'name',
                    /*ellipsis: true,
                    tooltip: true*/
                },
                {
                    title: '价格(元)',
                    key: 'finalPrice',
                    align: 'right',
                    width: 90,
                },
                /*{
                    title: '优惠',
                    key: 'discountName'
                }*/
            ],
            dataList: [],
            confirmSelection: [],
            selectionState: "",
            totalPriceWithoutDiscount: 0,
            totalPrice: 0,
            custormerDiscountRelationIdSelected: "",
            custormerDiscountList: [],
            remark: "",
            form: {
                email: ""
            },
            ruleValidate: {
                email: [
                    { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
                    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
                ]
            }
        }
    },
    computed: {
        docSelectedForOrder: {
            get() {
                /*注意getters的用法*/
                return this.$store.getters.docSelectedForOrder;
            },
            set(val) {
                //console.log('saveDocSelectedForOrder => ' + JSON.stringify(val));
                this.$store.commit('saveDocSelectedForOrder', val);
            }
        }
    },
    created() {

    },
    mounted() {
        this.$nextTick(() => {
            let docSelected = this.$store.getters.docSelected;
            if (docSelected.length > 0) {
                this.previewDoc(docSelected[0].id);
            }

            this.loadDocList();
            this.getCustomerDiscount();
            this.loadCustomerEmail();
        });
    },
    watch: {
        confirmSelection(val) {
            this.changeSelectionState(val);
        },
        custormerDiscountRelationIdSelected(val) {
            this.changeTotalPrice();
        }
    },
    beforeDestroy() {

    },
    methods: {
        nextStep() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    let emailAddress = this.form.email;
                    this.createOrder(emailAddress);
                } else {
                    this.$Message.error('请确认邮箱地址是否正确');
                }
            });
        },
        createOrder(emailAddress) {
            let docType = this.$route.params.docType;
            if (!docType) return;

            let formDataInStorage = this.$store.getters.docForm;
            if (!formDataInStorage) {
                formDataInStorage = {};
            }

            let docSelected = this.confirmSelection;
            if (docSelected.length === 0) {
                this.$notify.error({
                    title: '错误',
                    desc: '请至少选择一个文档.'
                });
                return;
            }

            let postJson = {};
            postJson.docs = this.confirmSelection; /*这个值是同步的，docSelectedForOrder是异步的*/
            postJson.params = formDataInStorage;
            postJson.remark = this.remark;
            postJson.docType = docType;
            postJson.address = emailAddress;

            if (!!this.custormerDiscountRelationIdSelected) {
                postJson.custormerDiscount = {};
                postJson.custormerDiscount.discountRelationId = this.custormerDiscountRelationIdSelected;
                let discount = this.custormerDiscountList.filter(
                    item => item.value === this.custormerDiscountRelationIdSelected);
                if (discount.length === 1) {
                    postJson.custormerDiscount.discountRelationVersion = discount[0].discountRelationVersion;
                } else {
                    delete postJson.custormerDiscount;
                }
            }

            //console.log('saveCustormerDiscount => ' + JSON.stringify(postJson.custormerDiscount));
            this.$store.commit('saveCustormerDiscount', postJson.custormerDiscount);

            API.createOrder({ formData: JSON.stringify(postJson) })
                .then((response) => {
                    console.log('saveOrder => ' + JSON.stringify(response.data));
                    this.$store.commit('saveOrder', response.data);
                    this.next(this.$route.name, { orderSN: response.data.sn });
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        backStep() {
            this.back(this.$route.name);
        },
        previewDoc(goodsId) {
            let formDataInStorage = this.$store.getters.docForm;

            let postJson = {};
            postJson.id = goodsId;
            postJson.params = formDataInStorage;

            API.previewDoc({ formData: JSON.stringify(postJson) })
                .then((response) => {
                    this.docHTML = response.data;
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        loadDocList() {
            let docSelected = this.$store.getters.docSelected;
            this.dataList = docSelected;

            let selection = [];
            if (!!this.docSelectedForOrder) { // 读取了computed中的 docSelectedForOrder
                this.dataList.map(item => {
                    let exist = this.docSelectedForOrder.some(it => {
                        return it.id === item.id;
                    })

                    if (exist) {
                        item._checked = true;
                        selection.push(item);
                    } else {
                        delete item._checked;
                    }
                })
            }

            this.confirmSelection = selection;
            this.changeSelectionState(this.docSelectedForOrder);
        },
        /*确认哪些文件成为订单内的文件*/
        onDocSelectChange(selection) {
            this.confirmSelection = selection;
            this.docSelectedForOrder = selection;
        },
        /*点击文件所在栏，可以在线预览该文件内容*/
        onRowClick(row) {
            this.previewDoc(row.id);
        },
        changeSelectionState(val) {
            this.selectionState = val.length + "/" + this.dataList.length;
            this.changeTotalPrice();
        },
        changeTotalPrice() {
            let confirmSelection = this.confirmSelection;
            let newTotal = 0;
            confirmSelection.map(item => {
                newTotal += item.finalPrice;
            })

            this.totalPriceWithoutDiscount = newTotal.toFixed(2);

            let custormerDiscountId = this.custormerDiscountRelationIdSelected;

            if (!custormerDiscountId) {
                /*如果没有优惠券，直接计算总价*/
                this.totalPrice = newTotal.toFixed(2);
                return;
            }

            API.calPriceWithDiscount({ price: newTotal.toFixed(2), discount_id: custormerDiscountId })
                .then((response) => {
                    this.totalPrice = response.data;
                })
        },
        getCustomerDiscount() {
            API.getCustomerDiscount({})
                .then((response) => {
                    let options = [];
                    let discounts = response.data;
                    discounts.map(item => {
                        let op = {};
                        op.label = item.name;
                        op.value = item.discountRelationId;
                        op.discountRelationVersion = item.discountRelationVersion;
                        options.push(op);
                    })
                    this.custormerDiscountList = options;

                    let custormerDiscount = this.$store.getters.custormerDiscount;
                    this.custormerDiscountRelationIdSelected = custormerDiscount.discountRelationId;
                })
        },
        loadCustomerEmail() {
            API.getCustomerEmailAddress({})
                .then((response) => {
                    this.form.email = response.data;
                }).catch((error) => {
                    console.log(error);
                });
        },
        saveEmailAddressAsDefault() {
            let emailAddress = this.form.email;
            API.saveEmailAddressAsDefault({ email: emailAddress })
                .then((response) => {
                    this.$notify.success({
                        title: this.$t('message.notice.success'),
                        desc: this.$t('message.notice.save_email_success')
                    });
                })
        }
    }
}
</script>